package com.blueflamedev.util
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.system.System;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;

	/**
	 * Outputs the framerate and memory usage of the flash movie. This can be turned on and off by blindly typing "getmemory".
	 * 
	 * @author Eric Smith
	 */	
	public class MemoryGauge extends Sprite
	{
		/**
		 * @private 
		 */		
		private var _tf:TextField;
		
		/**
		 * @private 
		 */	
		private var _format:TextFormat;
		
		/**
		 * @private 
		 */	
		private var _frm:FramerateMonitor;
		
		/**
		 * @private 
		 */	
		private var _blindPhrase:BlindPhrase;
		
		/** 
		 * The constructor
		 */		
		public function MemoryGauge(defaultOn:Boolean=false)
		{
			_format = new TextFormat("Arial, Helvetica, Verdana, _sans", 9, 0x888888, true);
			_tf = new TextField();
			_tf.background = true;
			_tf.backgroundColor = 0xFFFFFF;
			_tf.defaultTextFormat = _format;
			_tf.autoSize = TextFieldAutoSize.LEFT;
			addChild(_tf);
			if (!defaultOn)
				visible = false;
			addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		}
		
		private function onAddedToStage(event:Event):void
		{
			_frm = new FramerateMonitor(stage);
			_frm.addEventListener(Event.CHANGE, onFramerateChange);
			_blindPhrase = new BlindPhrase(stage, "getmemory");
			_blindPhrase.addEventListener(Event.COMPLETE, onBlindPhraseTyped);
			if (visible)
				_frm.start();
		}
		
		private function onFramerateChange(event:Event):void
		{
			_tf.text = "Memory: " + Math.round(flash.system.System.totalMemory / 1000).toString() + "KB\n" +
			"FPS: " + _frm.fps.toString() + "FPS";
		}
		
		private function onBlindPhraseTyped(event:Event):void
		{
			if (visible)
			{
				visible = false;
				_frm.stop();
			} else
			{
				visible = true;
				_frm.start();
			}
		}
	}
}